#include "drv_l1_sfr.h"
#include "drv_l1_tft2.h"
#include "drv_l1_gpio.h"
#include "drv_l2_display.h"
#include "drv_l1_timer.h"
#include "drv_l1_uart.h"
#include "board_config.h"

#if LCD_DRV_EN_TPO_TD025THD1

static void tpo_gpio_init(void)
{
	#if 0
	gpio_init_io(PANEL_IO_CSN, GPIO_OUTPUT);
	gpio_set_port_attribute(PANEL_IO_CSN, ATTRIBUTE_HIGH);

	gpio_init_io(PANEL_IO_SDA, GPIO_OUTPUT);
	gpio_set_port_attribute(PANEL_IO_SDA, ATTRIBUTE_HIGH);

	gpio_init_io(PANEL_IO_SCL, GPIO_OUTPUT);
	gpio_set_port_attribute(PANEL_IO_SCL, ATTRIBUTE_HIGH);
	#endif
}

static void cmd_delay(INT32U i)
{
	drv_msec_wait(i);
}

static void serial_cmd_1(INT32U cmd)
{
	INT32S	i;

	gpio_write_io(PANEL_IO_CSN, 1); //CS=1
	gpio_write_io(PANEL_IO_SCL, 0); //SCL=0
	gpio_write_io(PANEL_IO_SDA, 0); //SDA

	// set csn low
	gpio_write_io(PANEL_IO_CSN, 0); //CS=0
	cmd_delay(1);
	for(i = 0; i < 16; i++)
	{
		// shift data
		gpio_write_io(PANEL_IO_SDA, ((cmd & 0x8000) >> 15));	/* SDA */
		cmd = (cmd << 1);
		cmd_delay(1);

		// toggle clock
		gpio_write_io(PANEL_IO_SCL, 1);		//SCL=0
		cmd_delay(1);
		gpio_write_io(PANEL_IO_SCL, 0);		//SCL=0
		cmd_delay(1);
	}

	// set csn high
	gpio_write_io(PANEL_IO_CSN, 1);			//CS=1
	cmd_delay(1);
}

static INT32S tft_tpo_td025thd1_init(void)
{
	DBG_PRINT("%s\r\n", __func__);

	tpo_gpio_init();

	serial_cmd_1(0x0800);					//(0x02 << (2+8)) | 0x00);	//enable
#if 0
	serial_cmd_1((0x05 << (2 + 8)) | 0x10); //rotate
#endif
	R_TFT2_HS_WIDTH = 0;					//	1		=HPW
	R_TFT2_H_START = 1 + 239;				//	240		=HPW+HBP
	R_TFT2_H_END = 1 + 239 + 1280;			//	1520	=HPW+HBP+HDE
	R_TFT2_H_PERIOD = 1 + 239 + 1280 + 40;	//	1560	=HPW+HBP+HDE+HFP
	R_TFT2_VS_WIDTH = 0;					//	1		=VPW				(DCLK)
	R_TFT2_V_START = 21;					//	21		=VPW+VBP			(LINE)
	R_TFT2_V_END = 21 + 240;				//	261		=VPW+VBP+VDE		(LINE)
	R_TFT2_V_PERIOD = 21 + 240 + 1;			//	262		=VPW+VBP+VDE+VFP	(LINE)
	R_TFT2_LINE_RGB_ORDER = 0x00;

	drv_l1_tft2_signal_inv_set(TFT_VSYNC_INV | TFT_HSYNC_INV, (TFT_ENABLE & TFT_VSYNC_INV) | (TFT_ENABLE & TFT_HSYNC_INV));
	drv_l1_tft2_mode_set(TFT_MODE_UPS052);
	drv_l1_tft2_data_mode_set(TFT_DATA_MODE_8);
	drv_l1_tft2_clk_set(TFT_CLK_DIVIDE_8);	/* FS=66 */
	drv_l1_tft2_TFT_IO_enable(TRUE);
	drv_l1_tft2_en_set(TRUE);

	return STATUS_OK;
}

// tft table
DispCtrl_t TFT_Param_td025thd1 =
{
	/* lcd size */
	320,
	240,
	/* display position */
	0, //pos_x
	0, //pos_y 
	/* pip size */
	128,
	96,
	/* pip position */
	-128,	//x
	0,	//y
	/* lcd init & uninit */
	tft_tpo_td025thd1_init,
	NULL,
	/* lcd backlight control */
	LCD_BL_CTRL_CONSTANT,
	20 * 1000,	// in HZ for LCD_BL_CTRL_PWM
	55,			// in duty cycle for LCD_BL_CTRL_PWM
	/* tft format */
	DISP_FMT_GP420
};
#endif
